package com.von.utils;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

@Component
public class RestUtils {
    @Autowired
    private RestTemplate restTemplate;

    public <T> T get(String url, Class<T> clazz) {
        return restTemplate.getForObject(url, clazz);
    }

    public ResponseEntity get(String url, Map<String, String> header, Class clazz) {
        HttpHeaders headers = new HttpHeaders();
        Set<Map.Entry<String, String>> entries = header.entrySet();
        entries.forEach(a -> headers.add(a.getKey(), a.getValue()));
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        ResponseEntity exchange = restTemplate.exchange(url, HttpMethod.GET, requestEntity, clazz);
        return exchange;
    }


    public <T> T post(String url, Object object, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> formEntity = new HttpEntity<String>(JSONUtil.toJsonStr(object), headers);
        return restTemplate.postForObject(url, formEntity, clazz);
    }

    public <T> T post(String url, Map<String, String> header, Object object, Class<T> clazz) {
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        Set<Map.Entry<String, String>> entries = header.entrySet();
        entries.forEach(a -> headers.add(a.getKey(), a.getValue()));
        HttpEntity<String> formEntity = new HttpEntity<String>(JSONUtil.toJsonStr(object), headers);
        return restTemplate.postForObject(url, formEntity, clazz);
    }
}
